package com.kefu.exam.handler;

import cn.hutool.core.util.IdUtil;
import com.kefu.common.context.KefuContext;
import com.kefu.common.util.JacksonUtil;
import com.kefu.exam.enums.TipType;
import com.kefu.exam.mapper.ExamSubjectAnswerMapper;
import com.kefu.exam.mapper.ExamSubjectMapper;
import com.kefu.exam.model.ExamSubject;
import com.kefu.exam.model.ExamSubjectAnswer;
import com.kefu.exam.service.ExamSubjectService;
import com.kefu.exam.vo.ExamSubjectInsertVo;
import com.kefu.exam.vo.SubjectUnit;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 填空题的逻辑处理
 */
@Slf4j
public class VacancyHandler implements SubjectTipHandler {
    @Override
    public void subjectInitHandle(ExamSubject subject, ExamSubjectAnswerMapper subjectAnswerMapper, ExamSubjectMapper examSubjectMapper, KefuContext context) {
        //TODO 不需要执行
    }

    @Override
    public SubjectUnit expressTextSubject(ExamSubjectInsertVo vo, String subjectTypeId,
                                          KefuContext context, ExamSubjectService subjectService,
                                          ExamSubjectAnswerMapper subjectAnswerMapper, ExamSubjectMapper subjectMapper) {
        SubjectUnit unit = null;
        {
            //预处理
            ExamSubject subject = vo.convert();
            subject.setSubjectStatus(1);
            unit = subjectService.initSubjectUnit(subject, TipType.Vacancy, subjectTypeId, context);
        }
        {
            if (null != vo.getExamSubjectAnswerList() && vo.getExamSubjectAnswerList().size() > 0) {
                List<ExamSubjectAnswer> examSubjectAnswerList = vo.getExamSubjectAnswerList();
                for (int i = 0; i < examSubjectAnswerList.size(); i++) {
                    ExamSubjectAnswer answer = examSubjectAnswerList.get(i);
                    answer.setCreateTime(context.getNow());
                    answer.setCreateUser(context.getUserId());
                    answer.setCreateName(context.getUserName());
                    answer.setAnswerStatus(1);
                    answer.setAnswerSort(i);
                    answer.setAnswerId(IdUtil.simpleUUID());
                    answer.setSubjectId(unit.getSubject().getSubjectId());
                    int x = subjectAnswerMapper.insert(answer);
                    log.info("添加试题答案[{}]:{}", x, JacksonUtil.toString(answer));
                    unit.getSubject().setAnswerId(answer.getAnswerId());
                    int y = subjectMapper.updateByPrimaryKey(unit.getSubject());
                    log.info("更新试题正确答案信息[{}]:{}", y, JacksonUtil.toString(unit.getSubject()));
                }
            }
        }
        return unit;
    }

    @Override
    public int runPointWeight(SubjectUnit unit) {
        return 0;
    }
}
